import WxSdk from "../sdk/WxSdk";

export default class Http {

    public static sessionKey = 'sessionKey';

    constructor() {

    }


    /**
     * 
     * @param url 请求地址
     * @param method 请求方法，默认method
     * @param data 请求数据
     * @param onSuccess 成功回调，内部this指向null，如需使用请自行绑定
     * @param onFailed 失败回调，内部this指向null，如需使用请自行绑定
     */
    public static request(url: string, method: string, data: any, onSuccess: Function, onFailed: Function, retryTime: number = 3): void {
        if (WxSdk.isInWxDev()) {
            WxSdk.wxRequest({
                url: url,
                data: data,
                header: {
                    "Cookie": wx.getStorageSync(Http.sessionKey), 
                },
                method: method,
                success: (res) => {
                    if (res.header['Set-Cookie']) {
                        WxSdk.setStorageSync(Http.sessionKey, res.header['Set-Cookie']);                        
                    }
                    onSuccess && onSuccess(res.data);
                },
                fail: (err) => {
                    if (retryTime <= 0) {
                        onFailed && onFailed(err);
                    } else {
                        // 重试
                        Http.request(url, method, data, onSuccess, onFailed, retryTime - 1);
                    }
                }
            });

        } else {
            let httpClient = new Laya.HttpRequest();
            httpClient.once(Laya.Event.COMPLETE, null, (res) => {
                onSuccess && onSuccess(res);
                Http.offEvent(httpClient);
            });
            httpClient.once(Laya.Event.ERROR, null, (err) => {
                onFailed && onFailed(err);
                Http.offEvent(httpClient);
            });
            if (method.toUpperCase() === 'GET') {
                let tempArr: Array<string> = [];
                for (const key in data) {
                    if (data.hasOwnProperty(key)) {
                        const value = data[key];
                        tempArr.push(`${key}=${value}`);
                    }
                }
                url = `${url}?${tempArr.join('&')}`;
            } else {
                data = JSON.stringify(data);
            }
            httpClient.send(url, data, method, 'json');
        }
    }

    
    private static offEvent(httpClient: Laya.HttpRequest) {
        httpClient.offAll(Laya.Event.COMPLETE);
        httpClient.offAll(Laya.Event.ERROR);
        httpClient.offAll(Laya.Event.PROGRESS);
    }

    /**
     * Get请求方法
     * @param url 请求地址
     * @param data 请求数据，要求key value的形式
     * @param onSuccess 成功的回调，this指向null，如有需要请自行绑定
     * @param onFailed 失败的回到，this指向null，如有需要请自行绑定
     */
    public static Get(url: string, data: any = null, onSuccess: Function, onFailed: Function): void {
        return Http.request(url, 'GET', data, onSuccess, onFailed);
    }


    /**
     * Post请求方法
     * @param url 请求地址
     * @param data 请求数据，请求时会序列化成JSON字符串
     * @param onSuccess 成功的回调，this指向null，如有需要请自行绑定
     * @param onFailed 失败的回到，this指向null，如有需要请自行绑定
     */
    public static Post(url: string, data: any = null, onSuccess: Function, onFailed: Function): void {
        return Http.request(url, 'POST', data, onSuccess, onFailed);
    }

}
